/*
 * @Author: Lee 497232807@qq.com
 * @Date: 2023-07-27 16:02:16
 * @LastEditors: Lee 497232807@qq.com
 * @LastEditTime: 2023-07-27 17:23:28
 * @FilePath: \cocos_framework_base\extensions\h5_adpter\source\hooks.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import path from 'path';
import fs from 'fs';
import { IBuildTaskOption, BuildHook, IBuildResult } from '../@types';

interface IOptions {
    width: number;
    height: number;
}

const PACKAGE_NAME = 'h5_adpter';

interface ITaskOptions extends IBuildTaskOption {
    packages: {
        'cocos-plugin-template': IOptions;
    };
}

function log(...arg: any[]) {
    return console.log(`[${PACKAGE_NAME}] `, ...arg);
}

let allAssets = [];

export const throwError: BuildHook.throwError = true;

export const load: BuildHook.load = async function () {
    console.log(`[${PACKAGE_NAME}] Load cocos plugin example in builder.`);
    allAssets = await Editor.Message.request('asset-db', 'query-assets');
};

export const onBeforeBuild: BuildHook.onBeforeBuild = async function (options: ITaskOptions, result: IBuildResult) {
    // Todo some thing
    log(`${PACKAGE_NAME}.webTestOption`, 'onBeforeBuild');
};

export const onBeforeCompressSettings: BuildHook.onBeforeCompressSettings = async function (options: ITaskOptions, result: IBuildResult) {
    const pkgOptions = options.packages[PACKAGE_NAME];
    if (pkgOptions.webTestOption) {
        console.debug('webTestOption', true);
    }
    // Todo some thing
    console.debug('get settings test', result.settings);
};

export const onAfterCompressSettings: BuildHook.onAfterCompressSettings = async function (options: ITaskOptions, result: IBuildResult) {
    // Todo some thing
    console.log('webTestOption', 'onAfterCompressSettings');
};

export const onAfterBuild: BuildHook.onAfterBuild = async function (options: ITaskOptions, result: IBuildResult) {
    // change the uuid to test

    const pkgOptions: IOptions = options.packages[PACKAGE_NAME];
    log(`${PACKAGE_NAME}.webTestOption`, 'onAfterBuild====' + result.dest);

    dealHtml(result.dest, pkgOptions);

};

export const unload: BuildHook.unload = async function () {
    console.log(`[${PACKAGE_NAME}] Unload cocos plugin example in builder.`);
};

export const onError: BuildHook.onError = async function (options, result) {
    // Todo some thing
    console.warn(`${PACKAGE_NAME} run onError`);
};

export const onBeforeMake: BuildHook.onBeforeMake = async function (root, options) {
    console.log(`onBeforeMake: root: ${root}, options: ${options}`);
};

export const onAfterMake: BuildHook.onAfterMake = async function (root, options) {
    console.log(`onAfterMake: root: ${root}, options: ${options}`);
};

const dealHtml = function (dst, param) {
    let jsCode = `<script type="text/javascript">
    (function () {
        var userAgent = navigator.userAgent.toLowerCase();
        // 判断是否为移动端
        var isMobile = /mobile|android|iphone|ipad|phone/i.test(userAgent);
        var gameDiv = document.getElementById('GameDiv');
        var body = document.getElementsByTagName('body')[0];
        let orientation = 2 // 1 竖屏 2 横屏
        let isLobby = true //是否是大厅
        //是pc端
        if (!isMobile) {
            function setGameDiv(){
                var clientWidth = document.documentElement.clientWidth;
                var clientHeight = document.documentElement.clientHeight;
                var gameWidth;
                var gameHeight;
               

                if(isLobby) //大厅全屏
                {
                    gameWidth = clientWidth + 'px'
                    gameHeight = clientHeight + 'px'
                }
                else //游戏
                {
                    if(orientation == 1) //竖屏
                    {
                        var widthRatio = clientWidth / ${param.width};
                        var heightRatio = clientHeight /  ${param.height};
                        gameWidth = false ? '100%' :  ${param.width} * heightRatio;
                        gameHeight = false ?  ${param.height} * widthRatio : '100%';
                        if(gameWidth != '100%') {
                            gameWidth += 'px';
                        }
                        if(gameHeight != '100%') {
                            gameHeight += 'px';
                        }
                    }
                    else //横屏
                    {
                        gameWidth = clientWidth + 'px'
                        gameHeight = clientHeight + 'px'
                    }
                    
                }
                
                console.log('gameWidth',gameWidth,gameHeight)
                gameDiv.style.width = gameWidth
                gameDiv.style.height = gameHeight
                body.style.alignItems = 'center';
                body.style.justifyContent = 'center';
            }
            setGameDiv();
            window.onresize = function () {
                setGameDiv();
            }
            //修改canvas尺寸
            window.addEventListener('changeCanvasSize', (event)=> {
                orientation = event.detail.orientation;
                isLobby = event.detail.isLobby;
            });
        }
    })();
</script>`;
    //设置html
    const htmlPath = path.join(dst, "index.html");
    let data = fs.readFileSync(htmlPath, "utf8");
    const idx = data.indexOf('<script');
    const newStr = data.slice(0, idx) + '\n' + jsCode + '\n' + data.slice(idx - 1);
    fs.writeFileSync(htmlPath, newStr);

    // 设置application.js
    const srcFiles = fs.readdirSync(dst);
    for (let i = srcFiles.length - 1; i >= 0; i--) {
        var fileName = srcFiles[i];
        console.log("fileName",fileName)
        if (fileName.indexOf('application') >= 0) {
            console.log("fileName0",fileName)
            const filePath = path.join(dst, fileName);
            let data = fs.readFileSync(filePath, "utf8");
            var jsStr = data.replace("value: function start() {", "value: function start() {\n\t\t\t\t\t\tfunction isMobile() {\n\
                \tvar userAgent = navigator.userAgent.toLowerCase();\n\
                \t// 判断是否为移动端\n\
                \tvar isMobile = /mobile|android|iphone|ipad|phone/i.test(userAgent);\n\
                \t return isMobile;\n\
                \t}\n")
    
                jsStr = jsStr.replace("overrideSettings: {", "overrideSettings: {\n\
                \t\tscreen:{exactFitScreen:isMobile()},\n")
            fs.writeFileSync(filePath, jsStr);
        }
    }
    
};

